Skip to content

Conversation

@etr
Copy link
Owner

@etr etr commented Jan 30, 2026

Summary

This PR adds a centralized authentication mechanism to libhttpserver that runs before any resource's render method is called. This addresses issue #102 where users had to copy authentication code into every render_* method.

Features:

  • auth_handler: A callback that receives the http_request and can return nullptr to allow the request or an http_response to reject it
  • auth_skip_paths: A vector of paths that bypass authentication (supports exact match and wildcard suffix like /public/*)

Files changed:

  • src/httpserver/create_webserver.hpp - Added auth_handler_ptr typedef and builder methods
  • src/httpserver/webserver.hpp - Added member variables and helper declaration
  • src/webserver.cpp - Implemented auth check in request pipeline
  • test/integ/authentication.cpp - Added 10 new test cases
  • examples/centralized_authentication.cpp - New example file
  • README.md - Documentation for the new feature

Example Usage

webserver ws = create_webserver(8080)
    .auth_handler([](const http_request& req) -> std::shared_ptr<http_response> {
        if (req.get_user() != "admin" || req.get_pass() != "secret") {
            return std::make_shared<basic_auth_fail_response>("Unauthorized", "MyRealm");
        }
        return nullptr;  // Allow request
    })
    .auth_skip_paths({"/health", "/public/*"});

Test Plan

  • All existing tests pass (make check)
  • New tests added for:
    • Centralized auth rejection (401)
    • Centralized auth success (200)
    • Skip paths (exact match)
    • Skip paths (wildcard)
    • No partial prefix matching
    • Deep nested wildcard paths
    • POST method with auth
    • Wrong credentials
    • 404 for non-existent resources
    • Default behavior (no auth handler)
    • Multiple skip paths

Closes #102

Add auth_handler callback to webserver that runs before any resource's
render method. This allows defining authentication logic once for all
resources instead of duplicating it in every render method.

Features:
- auth_handler: callback that returns nullptr to allow request or
  http_response to reject
- auth_skip_paths: vector of paths to bypass auth (supports exact
  match and wildcard suffix like "/public/*")

Includes comprehensive tests and example in
examples/centralized_authentication.cpp
@etr etr force-pushed the feature/centralized-authentication-102 branch from c87865d to 7e1e360 Compare January 30, 2026 18:43
@etr etr merged commit 441f671 into master Jan 30, 2026
38 of 39 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Basic Authentication with libhttpserver v0.9.0

2 participants